let mongoose = require("mongoose");

// 添加更详细的连接日志
mongoose.connection.on("connected", () => {
  console.log("MongoDB connected successfully");
});

mongoose.connection.on("error", (err) => {
  console.log("MongoDB connection error:", err);
});

mongoose.connection.on("disconnected", () => {
  console.log("MongoDB disconnected");
});

mongoose
  .connect(
    "mongodb+srv://2334231668:xin123666@cluster0.13va5ah.mongodb.net/2409B",
    {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }
  )
  .then(() => {
    console.log("数据库连接成功！");
  })
  .catch((err) => {
    console.log("数据库连接失败:", err);
  });

// ======RBAC 系统相关表结构======

// RBAC 用户表
let RbacUser = new mongoose.Schema({
  _id: { type: String, required: true },           // 用户ID（字符串类型）
  userName: {type: String, required: true, unique: true},        // 用户名
  passWord: {type: String, required: true},        // 密码
  realName: {type: String, required: true},        // 真实姓名
  email: {type: String, required: true},           // 邮箱
  phone: {type: String, required: true},           // 手机号
  status: {                // 状态：active-启用，inactive-禁用
    type: String,
    default: 'active',
    enum: ['active', 'inactive']
  },
  createdAt: {             // 创建时间
    type: Date,
    default: Date.now
  },
  updatedAt: {             // 更新时间
    type: Date,
    default: Date.now
  },
  resetCode: {             // 密码重置验证码
    type: String,
    default: null
  },
  resetCodeExpires: {      // 验证码过期时间
    type: Date,
    default: null
  },
});

// 权限表
let Permission = new mongoose.Schema({
  _id: { type: String, required: true },           // 权限ID（字符串类型）
  name: {type: String, required: true},            // 权限名称
  code: {type: String, required: true, unique: true},            // 权限代码（唯一）
  description: {type: String, default: ''},     // 权限描述
  parentId: {type: String},          // 上级权限ID：线性数据库表示树形结构
  path: {type: String, required: true, unique: true},     // 权限路径
  icon: {type: String, default: ''},     // 图标
  sort: {type: Number, default: 0},     // 排序
  isShow: {type: Boolean, default: false},     // 是否显示
  status: {                // 是否启用
    type: String,
    default: 'active',
    enum: ['active', 'inactive']
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

// 角色表
let Role = new mongoose.Schema({
  _id: { type: String, required: true },           // 角色ID（字符串类型）
  name: {type: String, required: true},            // 角色名称
  code: {type: String, required: true, unique: true},            // 角色代码（唯一）
  description: {type: String, default: ''},     // 角色描述
  status: {                // 是否启用
    type: String,
    default: 'active',
    enum: ['active', 'inactive']
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

// 角色权限关联表
let RolePermission = new mongoose.Schema({
  roleId: {                // 角色ID
    type: String,
    required: true
  },
  permissionId: {          // 权限ID
    type: String,
    required: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

// 用户角色关联表
let UserRole = new mongoose.Schema({
  userId: {                // 用户ID
    type: String,
    required: true
  },
  roleId: {                // 角色ID
    type: String,
    required: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

// ======移动端相关表结构======

// 登录注册专用表
let User = new mongoose.Schema({
  userName: String,
  passWord: String,
});

// 分类表
let classify = new mongoose.Schema({
  name: String,
});

// 商品表 - 基于goods.json结构
let Goods = new mongoose.Schema({
  id: { type: String, required: true, unique: true },           // 商品ID
  title: { type: String, required: true },                      // 商品标题
  image: { type: String, required: true },                      // 商品图片
  category: { type: String, required: true },                   // 商品分类
  tags: { type: Array, default: [] },                                     // 活动标签数组
  activity: { type: Array, default: [] },                                 // 活动类型数组（限时秒杀、特惠拼团）
  currentPrice: { type: Number, required: true },               // 现价
  originalPrice: { type: Number, required: true },              // 原价
  stock: { type: Number, required: true },                      // 库存
  sales: { type: Number, default: 0 },                          // 销量
  description: { type: String },                // 商品描述
  unit: { type: String },                       // 商品规格单位
  createdAt: { type: Date, default: Date.now },                 // 创建时间
  updatedAt: { type: Date, default: Date.now }                  // 更新时间
});

// 用户表
let YonghuUser = new mongoose.Schema({
  id: { type: String, required: true, unique: true }, // 用户ID
  userName: { type: String, required: true, unique: true }, // 用户名
  nickname: { type: String, required: true },      // 昵称
  avatar: { type: String, default: '' },           // 头像
  phone: { type: String, required: true },         // 手机号
  email: { type: String, required: true },         // 邮箱
  passWord: { type: String, required: true },      // 密码
  vipLevel: { type: Number, default: 0 },          // VIP等级
  points: { type: Number, default: 0 },            // 积分
  verified: { type: Boolean, default: false },     // 是否验证
  gender: { type: String, enum: ['男', '女', '保密'], default: '保密' }, // 性别
  city: { type: String, default: '' },             // 城市
  registerTime: { type: Date, default: Date.now }, // 注册时间
  lastLoginTime: { type: Date, default: Date.now }, // 最后登录时间
  status: { 
    type: String, 
    default: 'active',
    enum: ['active', 'inactive']
  },                                                // 状态
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

// 优惠券模型
let YonghuCoupon = new mongoose.Schema({
  id: { type: String, required: true, unique: true }, // 优惠券ID
  userId: { type: String, required: true },         // 用户ID
  couponId: { type: String, required: true },       // 优惠券编号
  name: { type: String, required: true },           // 优惠券名称
  type: { type: String },           // 优惠券类型
  discount: { type: Number, required: true },       // 优惠金额
  minAmount: { type: Number, default: 0 },         // 最低消费金额
  category: { type: String },       // 使用范围
  status: { 
    type: String, 
    default: '可使用',
    enum: ['可使用', '已使用', '已过期']
  },
  startTime: { type: Date, required: true },        // 开始时间
  endTime: { type: Date, required: true },          // 结束时间
  description: { type: String, default: '' },       // 描述
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

// 订单模型
let YonghuOrder = new mongoose.Schema({
  id: { type: String, required: true, unique: true }, // 订单ID
  userId: { type: String, required: true },         // 用户ID
  orderId: { type: String, required: true },        // 订单号自动生成
  products: { type: Array, default: [] },
  totalQuantity: { type: Number, required: true }, // 订单总数量
  status: { 
    type: String, 
    default: '待付款',
    enum: ['待付款', '待发货', '待提货', '待评价', '退款中', '已退款', '退款失败', '已取消']
  },
  orderTime: { type: Date, default: Date.now },
  paymentMethod: { type: String, default: '支付宝' },
  deliveryAddress: { type: String, default: '保定市莲池区南大园乡河北科技学院' },
  caption: { type: String, default: 'A' },    // 团长
  pickupCode: { type: String, default: '' },   // 提货码
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

// 历史记录模型
let History = new mongoose.Schema({
  id: { type: String, required: true, unique: true }, // 历史记录ID
  userId: { type: String, required: true },         // 用户ID
  orderId: { type: String, required: true },        // 订单号
  historyList: { type: Array, default: [] },
});


// 创建移动端相关模型
let ClassifysModel = mongoose.model("classifys", classify, "classifys");

// 创建 RBAC 相关模型
let RbacUserModel = mongoose.model("RbacUser", RbacUser, "User_hy");
let PermissionModel = mongoose.model("Permission", Permission, "Permission_hy");
let RoleModel = mongoose.model("Role", Role, "Role_hy");
let RolePermissionModel = mongoose.model("RolePermission", RolePermission, "RolePermission_hy");
let UserRoleModel = mongoose.model("UserRole", UserRole, "UserRole_hy");

// 创建移动端用户相关模型
let YonghuUserModel = mongoose.model("User_yonghu", YonghuUser, "User_yonghu");
let YonghuOrderModel = mongoose.model("Order", YonghuOrder, "Order");
let YonghuCouponModel = mongoose.model("Coupon", YonghuCoupon, "Coupon");

// 创建登录注册专用模型
let UserModel = mongoose.model("User", User, "User");

// 创建商品模型
let GoodsModel = mongoose.model("goods", Goods, "goods");


// 创建历史记录模型
let HistoryModel = mongoose.model("history", History, "history");

module.exports = { 
  RbacUserModel,            // RBAC 用户表
  PermissionModel,          // 权限表
  RoleModel,                // 角色表
  RolePermissionModel,      // 角色权限关联表
  UserRoleModel,            // 用户角色关联表
  YonghuUserModel,           // 用户表
  YonghuOrderModel,          // 订单表
  YonghuCouponModel,         // 优惠券表
  ClassifysModel,            // 商品分类表
  GoodsModel,                 // 商品表（新）
  UserModel,                  // 登录注册专用表
  HistoryModel,               // 历史记录表
};
